//
//  FQDHomeFeedViewController.m
//  FakeQDaily
//
//  Created by mewxiv on 8/12/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDHomeFeedViewController.h"
#import "FQDMainViewController.h"
#import "FQDArticleDetailViewController.h"
#import "FQDSimpleWebViewController.h"
#import "FQDColumnArticleFeedViewController.h"
#import "UIViewController+FQDStatusBar.h"

#import "FQDLabPapersFeedCellItemProvider.h"
#import "FQDHomeFeedCellItemProvider.h"

#import "FQDMainQButton.h"
#import "FQDRestModel.h"

#import "FQDBannerHeaderView.h"
#import "FQDHomeFeedCell.h"
#import "FQDFeedCellItem.h"
#import "FQDColumnFeedCellItem.h"

@interface FQDHomeFeedViewController () <UICollectionViewDelegate,
                                         UICollectionViewDataSource,
                                         UICollectionViewDelegateFlowLayout,
                                         UIScrollViewDelegate>

// 记录上次的滚动偏移量
@property (nonatomic, assign) CGFloat lastTranslationY;
// Cell数据供应者
@property (nonatomic, strong) FQDHomeFeedCellItemProvider *provider;
// 获取UICollectionView所有可视的HeaderView的列表
// NSMapTable存放当前所有可视的HeaderView的弱引用，当HeaderView不可见被释放时，字典中对应项也会被移除
@property (nonatomic, strong) NSMapTable *visibleReuseHeaderViews;

@end

@implementation FQDHomeFeedViewController
@dynamic provider;

#pragma mark View life cycle

- (void)viewDidLoad {
    [super viewDidLoad];

    self.hidesNavigationView = YES;
    [self setupCellItemProvider];
    [self setupBannerHeaderView];
    [self setupNotifications];
    [self loadNewCellItemsWithCompletion:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupCellItemProvider
{
    self.provider = [[FQDHomeFeedCellItemProvider alloc] init];
}

- (void)setupBannerHeaderView
{
    [self.feedCollectionView registerClass:[FQDBannerHeaderView class]
            forSupplementaryViewOfKind:[FQDBannerHeaderView kind]
                   withReuseIdentifier:[FQDBannerHeaderView reuseId]];
    
}

- (void)setupNotifications
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(postDataDidChange:)
                          name:FQDPostDataDidChangeNotification object:nil];
}

#pragma mark - Notifications
- (void)postDataDidChange:(NSNotification *)note
{
    NSDictionary *userInfo = note.userInfo;
    FQDPost *post = userInfo[kQDailyPostDataUserInfoKey];
    if (post) {
        NSArray *allFeeds = self.provider.cellItems;
        for (FQDFeedCellItem *cellItem in allFeeds) {
            if ([cellItem.restModel isKindOfClass:[FQDFeed class]]) {
                FQDFeed *feed = (FQDFeed *)cellItem.restModel;
                if ( [feed.post.ID isEqualToString:post.ID]) {
                    feed.post = post;
                    [self reloadData];
                }
            }
        }
    }
}

#pragma mark - Getters and Setters
- (NSMapTable *)visibleReuseHeaderViews
{
    if (!_visibleReuseHeaderViews) {
        _visibleReuseHeaderViews = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory
                                    valueOptions:NSMapTableWeakMemory];
    }
    return _visibleReuseHeaderViews;
}

- (FQDBannerHeaderView *)bannerHeader
{
    NSIndexPath *headerIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    FQDBannerHeaderView *header = (FQDBannerHeaderView *)
    [self.visibleReuseHeaderViews objectForKey:headerIndexPath];
    return header;
}

#pragma mark - Override methods
- (NSArray *)cellClasses
{
    NSArray *superCellClasses = [super cellClasses];
    NSArray *extraCellClasess = @[
        [FQDHeadlineFeedCell class],
        [FQDRegularArticleADFeedCell class],
    ];
    return [superCellClasses arrayByAddingObjectsFromArray:extraCellClasess];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 0, 0, 0);
}

- (void)presentCellItem:(FQDFeedCellItem *)cellItem atIndexPath:(NSIndexPath *)indexPath
{
    if ([cellItem.restModel isKindOfClass:[FQDAdFeed class]]) {
        FQDAdFeed *adFeed = (FQDAdFeed *)cellItem.restModel;
        
        FQDSimpleWebViewController *swVC = [[FQDSimpleWebViewController alloc] init];
        swVC.urlString = adFeed.advertisement.ad_url;
        [self.navigationController pushViewController:swVC animated:YES];
    } else if ([cellItem.restModel isKindOfClass:[FQDHeadline class]]) {
        FQDFeed *castFeed = (FQDFeed *)cellItem.restModel;
        FQDArticleDetailViewController *articleDetailVC = [[FQDArticleDetailViewController alloc] init];
        articleDetailVC.post = castFeed.post;
        [self.navigationController pushViewController:articleDetailVC animated:YES];
    }
    else {
        [super presentCellItem:cellItem atIndexPath:indexPath];
    }
}

#pragma mark - FQDBaseCellActionDelegate
- (void)collectionViewCell:(FQDFeedCollectionViewCell *)cell actionType:(NSInteger)actionType actionControl:(UIControl *)control userInfo:(NSDictionary *)userInfo
{
    if ([cell isKindOfClass:[FQDLabFeedCell class]]) {
        if (actionType == FQDLabFeedCellActionTitleBarClicked) {
            FQDLabPapersFeedCellItemProvider *provider = [[FQDLabPapersFeedCellItemProvider alloc] init];
            FQDArticleFeedBaseViewController *afbVC = [[FQDArticleFeedBaseViewController alloc] init];
            afbVC.title = @"好奇心研究所";
            afbVC.provider = provider;
            [self.navigationController pushViewController:afbVC animated:YES];
        }
    } else if ([cell isKindOfClass:[FQDColumnFeedCell class]]) {
        if (actionType == FQDColumnFeedCellActionTitleBarClicked) {
            FQDColumnFeedCellItem *columnCellItem = (FQDColumnFeedCellItem *)cell.cellItem;
            FQDColumn *column = columnCellItem.column;
            FQDColumnArticleFeedViewController *feedVC = [[FQDColumnArticleFeedViewController alloc] init];
            feedVC.column = column;
            [self.navigationController pushViewController:feedVC animated:YES];
        }
    }
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(collectionView.frame.size.width, 256.0f);
}

#pragma mark - UICollectionViewDataSource
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *supplementView = nil;
    if (kind == [FQDBannerHeaderView kind]) {
        FQDBannerHeaderView *header = (FQDBannerHeaderView *)
        [collectionView dequeueReusableSupplementaryViewOfKind:[FQDBannerHeaderView kind]
                                           withReuseIdentifier:[FQDBannerHeaderView reuseId]
                                                  forIndexPath:indexPath];
        header.banners = self.provider.banners;
        supplementView = header;
        
        [self.visibleReuseHeaderViews setObject:header forKey:indexPath];
    }
    
    return supplementView;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    if ([elementKind isEqualToString:[FQDBannerHeaderView kind]]) {
        self.fqd_statusBarStyle = FQDStatusBarStyleLightTranslucent;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
{
    if ([elementKind isEqualToString:[FQDBannerHeaderView kind]]) {
        self.fqd_statusBarStyle = FQDStatusBarStyleDarkOpaque;
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    FQDBannerHeaderView *header = [self bannerHeader];
    if (header) {
        [header pauseAutoScroll];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    FQDBannerHeaderView *header = [self bannerHeader];
    if (header) {
        [header resumeAutoScroll];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        CGFloat const moveMaxY = 50.0f;
        // 下面的计算比较耗时
        CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView];
        
        if ((self.lastTranslationY <= moveMaxY && translation.y > moveMaxY) ||
            (self.lastTranslationY >= -moveMaxY && translation.y < -moveMaxY)) {
            
            FQDMainViewController *mainVC = (FQDMainViewController *)self.parentViewController;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (translation.y > moveMaxY) {
                    [UIView animateWithDuration:0.5f animations:^{
                        mainVC.qButton.alpha = 1;
                    }];
                } else if (translation.y < -moveMaxY) {
                    [UIView animateWithDuration:0.5f animations:^{
                        mainVC.qButton.alpha = 0;
                    }];
                }
            });
        }
        self.lastTranslationY = translation.y;
    });
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    FQDMainViewController *mainVC = (FQDMainViewController *)self.parentViewController;
    if (mainVC.qButton.alpha < 1) {
        [UIView animateWithDuration:0.5f animations:^{
            mainVC.qButton.alpha = 1;
        }];
    }
}

@end
